package com.lucas_main.uvicultimate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;



import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;

public class ViewThreadsActivity extends Activity {
	//This is just a test
	ListView listV;
	DBAdapter db = new DBAdapter(this);
	
	private View mThreadListView;
	private View mThreadListStatusView;
	TextView mThreadListStatusMessageView;
	private GetThreadsTask mGetThreadsTask = null;
	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_threads);
		// Show the Up button in the action bar.
		setupActionBar();
		
		mThreadListView = findViewById(R.id.list_view_threads);
		mThreadListStatusView = findViewById(R.id.get_thread_status);
		mThreadListStatusMessageView = (TextView) findViewById(R.id.get_threads_status_message);
		
		
		showProgress(true);
		mGetThreadsTask = new GetThreadsTask();
		//ThreadsUpdated true = local search, false = online search
		mGetThreadsTask.execute();
		
		
	}
	private void populateListView(String [] ThreadList){
		
		try{					
			listV = (ListView) findViewById(R.id.list_view_threads);
			
			//TODO: Make this array adapter into a list adapter so that we can manipulate it easier	
			listV.setAdapter(new ArrayAdapter<String> (this,
					R.layout.single_thread_item, ThreadList));			
			listV.setTextFilterEnabled(true);			
			listV.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					// TODO Call upon the view thread view
					Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show();
				}
				
			});
			
		}
		catch (Exception e){
			Log.e("Problem in On Create", e.toString());
		}
	}
	
	public class GetThreadsTask extends AsyncTask<Void, Void, JSONArray> {
		@Override
		protected JSONArray doInBackground(Void... params) {
			// attempt authentication against a network service.
			SharedPreferences setting =  getSharedPreferences("booleans", Context.MODE_PRIVATE);
			boolean threadsUpdated = setting.getBoolean("threadsUpdated", false);
			
			if (!threadsUpdated){				
				Log.d("Going Online", "Checking online " + threadsUpdated);
				try {
					HttpClient httpclient = new DefaultHttpClient();				
					HttpPost httpPost = new HttpPost ("http://www.uvicultimate.com/apps/get_thread_list.php?forumType=men"); //TODO: Change to make the women's forum show as well.
					HttpResponse response = httpclient.execute(httpPost);
					
					//Read in the content in pure form
					BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
					StringBuilder builder = new StringBuilder();				
					for (String line = null; (line = reader.readLine()) !=null; ) {
						builder.append(line).append("\n");
					}	
					//Get the string into an array
					JSONArray finalResult = new JSONArray(new JSONTokener(builder.toString()));
					return finalResult;
				} catch (Exception e) {
					Log.e("log_tag", "Error in http connection " + e.toString());
					JSONArray arr = new JSONArray();
					return arr;
				}
			} else {
				Log.d("Not online", "Checking local");
				JSONArray arr = new JSONArray();
				return arr;
			}
		}

		@Override
		protected void onPostExecute(JSONArray threadArray) {
			//Threads are updated
			Log.d("DEBUG", "Inside onPostExecute threadArray is " + threadArray.isNull(0));
			if (threadArray.isNull(0)) {
				//TODO: Get threads from local database
				db.open();
				int i = db.getUserGender();
				Log.d("DEBUG", "About to get threads");
				try{
					Cursor mCursor = db.getThreads();
					String [] ThreadList = new String [mCursor.getCount()];
					mCursor.moveToFirst();
					i = 0;
					while (mCursor.moveToNext()) {
						ThreadList[i] = mCursor.getString(0);
						i++;
					}
					Log.d("DEBUG", "About to populate list view");
					populateListView(ThreadList);
				} catch (Exception e) {
					Log.e("Thread Grab Problem", e.toString());
				}	
				Log.d("DEBUG", "leaving onPostExecute Status = " + i);
				showProgress(false);	
				
			} else {
				showProgress(false);			
				try{					
					JSONObject obj = new JSONObject();
					String [] ThreadList = new String[threadArray.length()];	
					int i = 0;
	                for (i = 0; i < threadArray.length(); i++) {
	                	ThreadList[i] = threadArray.getJSONObject(i).get("subject").toString();                	                	
	                }
	                
	    			if (i > 0) {
	    				populateListView(ThreadList);
	    				if (updateLocalThreads(threadArray)){
	    					SharedPreferences setting =  getSharedPreferences("booleans", Context.MODE_PRIVATE);
	        				SharedPreferences.Editor editor = setting.edit();
	        				editor.putBoolean("threadsUpdated", true);
	        				editor.commit();
	    				}  				
	    			} else {
	    				Log.e("List Error", "Error parsing list");
	    			}
		        }
		        catch(Exception e){
		                Log.e("log_tag", "Error  converting result "+e.toString());
		        }
			}
		}
	}
	
	private boolean updateLocalThreads(JSONArray newArray){
		
		//TODO: Loop through each array, convert to object, get all items punch into database
		try{
			
			JSONObject obj = new JSONObject();
			db.open();
			for (int i = 0; i < newArray.length(); i++){
				
					obj = newArray.getJSONObject(i);
					db.insertThread(obj.getInt("id"), obj.getString("author_names"), obj.getInt("last_update"),
							obj.getString("subject"), obj.getInt("time_posted"), obj.getInt("status"), obj.getInt("last_msg_id"), 
							obj.getInt("num_replies"), obj.getString("body"), "men");
			} 
			
			Log.d("DB Access Complete", "Completed Updating the DB");
			db.close();
			return true;
			
		} catch (Exception e) {
			Log.e("JSON Exception", "Problem parsing JSON Array into local DB");
			return false;
		}
		
	}
	
	/**
	 * Shows the progress UI and hides the login form.
	 */
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		Log.d("", "Got inside ok");
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);
			Log.d("", "Build Version OK");
			mThreadListStatusView.setVisibility(View.VISIBLE);
			mThreadListStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mThreadListStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mThreadListView.setVisibility(View.VISIBLE);
			mThreadListView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mThreadListView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mThreadListStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mThreadListView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}


	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.

	 */
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_threads, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onDestroy() {
		
		super.onDestroy();
		SharedPreferences setting =  getSharedPreferences("booleans", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = setting.edit();
		editor.clear();
		editor.commit();
	}

}
